var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})
var express = require('express')
var db = require('../db.js')
var md5 = require('md5-nodejs')
var multer = require('multer');
var router = express.Router()


//随机获取50条数据
router.get('/mode', async function (req, res) {
    let {
        pageSize = 50
    } = req.query
    let sql = `select * from questions order by rand() limit ${pageSize}`
    let data = await db.doSQL(sql)
    res.send(db.handerResult(data))
})




//题库获取
router.get('/testQuestionslist', async function (req, res) {
    var {
        pageSize,
        currentPage,
        keyword,
        sort = "desc",
        orderby = "id"
    } = req.query

    if (!currentPage) {
        currentPage = 0
    }

    if (!pageSize) {
        pageSize = 10
    }

    var sql = `select q.id, q.title, q.options, q.answers, q.tips, q.created,q.cid, c.name as type , u.name as author from questions as q, question as c, user as u where q.uid = u.id and c.id = q.cid`
    var sql_count = "select count(*) as total from questions";

    var num = currentPage * pageSize;
    if (keyword) {
        sql_count += ` where title like '%${keyword}%'`;
        sql += ` and q.title like '%${keyword}%'`;
    }
    if (orderby) {
        sql += ` order by ${orderby} ${sort}`;
    }
    sql += ` limit ${num},${pageSize}`
    sql_question = 'select * from question'
    const data = await Promise.all([db.doSQL(sql), db.doSQL(sql_count), db.doSQL(sql_question)])
    res.send(db.handerResult(data[0].data, data[1].data))
})



//新增题
router.post('/addList', urlencodedParser, async function (req, res) {
    let {
        title,
        options,
        answers,
        tips,
        uid,
        cid
    } = req.body
    var sql = `insert into questions (title,options,answers,tips,uid,cid) values ('${title}','${options}','${answers}','${tips}','${uid}','${cid}')`
    let data = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

// 删除
router.get('/deleOption', async function (req, res) {
    var ids = req.query.id
    // console.log(ids)
    var sql = `delete from questions where id in (${ids})`
    const data = await db.doSQL(sql)
    res.send(db.handerResult(data))
})



//修改题
router.post('/upList', urlencodedParser, async function (req, res) {
    let {
        id,
        title,
        options,
        answers,
        tips,
        uid,
        cid
    } = req.body
    var sql = `update questions set title = '${title}',options='${options}',answers='${answers}',tips='${tips}',uid='${1}' ,cid='${cid}' where id = '${id}'`
    var data = await db.doSQL(sql)
    res.send(db.handerResult(data))
})



module.exports = router;